﻿using Architecture.CrossCutting.Common.Network;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Architecture.CrossCutting.Common.Logging
{
    public abstract class BaseLog
    {
        public Guid Id { get; private set; }
        public Guid CorrelationId { get; private set; }
        public System.Diagnostics.TraceLevel Level { get; private set; }
        public DateTime Created { get; private set; }
        public Int32 ThreadId { get; private set; }
        public Int32 ProcessId { get; private set; }
        public string ServerName { get; private set; }             
        public string ServerIp { get; private set; }               
        public String ThreadIdentity { get; private set; }
        public String WindowsIdentity { get; private set; }


        public BaseLog()
        {
            this.Initialize();
        }

        internal void Initialize()
        {
            this.UpdateExecutionContext();

            this.Level = System.Diagnostics.TraceLevel.Verbose;
            this.ServerName = Environment.MachineName;
            this.ServerIp = IpManagement.GetLocalIPAddress();
            this.Created = DateTime.UtcNow;
        }

        public void UpdateExecutionContext()
        {
            this.Id = Guid.NewGuid();
            this.CorrelationId = CustomContext.Current.ExecutionId;
            this.UpdateThreadInformation();
        }

        internal void UpdateThreadInformation()
        {
            this.ProcessId = Process.GetCurrentProcess().Id;
            this.ThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId;
            var currentPrincipal = System.Threading.Thread.CurrentPrincipal;
            if ((currentPrincipal.Identity != null) && currentPrincipal.Identity.IsAuthenticated)
            {
                this.ThreadIdentity = System.Threading.Thread.CurrentPrincipal.Identity.Name;
            }
            else
            {
                this.ThreadIdentity = "Anonymous";
            }

            System.Security.Principal.WindowsIdentity current = System.Security.Principal.WindowsIdentity.GetCurrent();
            if (current != null)
            {
                this.WindowsIdentity = current.Name;
            }            
        }
        

    }
}
